package com.shchuangzhi.smartguard;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.elvishew.xlog.XLog;
import com.shchuangzhi.smartguard.core.Consts;
import com.shchuangzhi.smartguard.core.DBHelper;
import com.shchuangzhi.smartguard.core.Mode;
import com.shchuangzhi.smartguard.core.School;
import com.shchuangzhi.smartguard.core.User;
import com.shchuangzhi.smartguard.core.Util;
import com.shchuangzhi.smartguard.core.receiver.ReceiverInOutData;
import com.shchuangzhi.smartguard.fragment.Receiver;

import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by j_hu on 8/3/17.
 */

public class TitleBar {
    private Activity activity;
    private DBHelper dbHelper;
    private static final int CONNECT_TIME_OUT = 3000;
    private static final int READ_TIME_OUT = 3000;

    public TitleBar(Activity activity, DBHelper dbHelper) {
        this.activity = activity;
        this.dbHelper = dbHelper;
    }

    public TitleBar init() {
        ImageView metaView = (ImageView)activity.findViewById(R.id.title_meta_view);
        if (metaView != null) {
            metaView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int[] array = dbHelper.getMetaCountArray();
                    final String[] items = {
                            String.format(Consts.META_GRADE_COUNT, array[0]),
                            String.format(Consts.META_CLASS_COUNT, array[1]),
                            String.format(Consts.META_DEPT_COUNT, array[2]),
                            String.format(Consts.META_DUTY_COUNT, array[3]),
                            String.format(Consts.META_STUDENT_COUNT, array[4]),
                            String.format(Consts.META_TEACHER_COUNT, array[5]),
                            String.format(Consts.META_STUDENT_CARD_COUNT, array[6]),
                            String.format(Consts.META_TEACHER_CARD_COUNT, array[7]),
                    };

                    AlertDialog.Builder listDialog =
                            new AlertDialog.Builder(activity);
                    listDialog.setTitle(Consts.META_COUNT_TITLE);
                    listDialog.setItems(items, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    });
                    listDialog.show();
                }
            });
        }

        ImageView dbUploadView = (ImageView)activity.findViewById(R.id.title_sync_log_db);
        if (dbUploadView != null) {
            dbUploadView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (activity != null) {
                        SharedPreferences prefs = activity.getSharedPreferences(Consts.APP_FULL_NAME, Context.MODE_PRIVATE);
                        new AsyncUploadTask(activity).execute(
                                prefs.getString("network_preference", ""),
                                prefs.getString("terminal_name_preference", ""));
                    }
                }
            });
        }

        User user = User.get();
        if (user != null) {
            if (!User.get().isAdmin()) {
                dbUploadView.setVisibility(View.INVISIBLE);
            } else {
                dbUploadView.setVisibility(View.VISIBLE);
            }
        } else {
            if (activity != null) {
                Intent intent = new Intent(activity, LoginActivity.class);
                activity.startActivity(intent);
                activity.finish();
            }
        }

        ImageView versionView = (ImageView)activity.findViewById(R.id.title_app_version);
        if (versionView != null) {
            versionView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    final String[] items = {Util.getVersion(activity)};
                    AlertDialog.Builder listDialog =
                            new AlertDialog.Builder(activity);
                    listDialog.setTitle(Consts.TITLE_APP_ABOUT);
                    listDialog.setItems(items, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    });
                    listDialog.show();
                }
            });
        }

        return this;
    }

    public void loadTitle(String title) {
        TextView view = (TextView)activity.findViewById(R.id.text_title);
        if (view != null) {
            if (title != null && title.length() > 0) {
                view.setText(title);
            } else {
                School school = dbHelper.getSchool();
                if (school != null) {
                    view.setText(String.format("%s - %s", school.getName(),
                            Mode.getInstance().getCurrent() == Consts.IN_MODE ? Consts.IN_MODE_NAME : Consts.OUT_MODE_NAME));
                }
            }
        }
    }

    public void loadReceiverTitle() {
        TextView view = (TextView)activity.findViewById(R.id.text_title);
        view.setText(String.format("%s - %s",
                ReceiverInOutData.getInstance().getSchoolName(),
                ReceiverInOutData.getInstance().getStats().getClassName()));

        ReceiverInOutData.InOutStats stats = ReceiverInOutData.getInstance().getStats();

        view = (TextView)activity.findViewById(R.id.txt_attend_count);
        view.setText(stats.getShouldAttendCount().toString());

        view = (TextView)activity.findViewById(R.id.txt_health_count);
        view.setText(stats.getHealthCount().toString());

        view = (TextView)activity.findViewById(R.id.txt_watch_count);
        view.setText(stats.getWatchCount().toString());

        view = (TextView)activity.findViewById(R.id.txt_sick_count);
        view.setText(stats.getSickCount().toString());

        view = (TextView)activity.findViewById(R.id.txt_bye_count);
        view.setText(stats.getByeCount().toString());

        view = (TextView)activity.findViewById(R.id.txt_absence_count);
        view.setText(stats.getAbsenceCount().toString());

        view = (TextView)activity.findViewById(R.id.txt_no_bye_count);
        //未接走=应出勤-缺席-已接走
        view.setText(new Integer(stats.getShouldAttendCount() - stats.getAbsenceCount() - stats.getByeCount()).toString());
    }

    private class AsyncUploadTask extends AsyncTask<String, Void, Boolean> {
        private Activity activity;
        public AsyncUploadTask(Activity activity) {
            this.activity = activity;
        }

        @Override
        protected Boolean doInBackground(String... params) {
            boolean isOk = false;
            InputStream in = null;
            OutputStream out = null;
            HttpURLConnection conn = null;
            try {
                if (!params[0].equals("")) {
                    DBHelper.DumpSummary summary = dbHelper.dump();
                    if (summary.size() > 0) {
                        URL url = new URL(String.format("%s?type=db&name=%s&crc=%s", String.format("%s/smartguard/v1/api/upload", params[0].replaceAll("/$","")), params[1], summary.crc()));
                        XLog.d(url.toString());
                        conn = (HttpURLConnection)url.openConnection();
                        conn.setDoOutput(true);
                        conn.setRequestMethod("POST");
                        conn.setUseCaches(false);
                        conn.setConnectTimeout(CONNECT_TIME_OUT);
                        conn.setReadTimeout(READ_TIME_OUT);
                        out = new DataOutputStream(conn.getOutputStream());
                        out.write(summary.binary());
                        out.flush();
                        isOk = conn.getResponseCode() == 200;
                    }
                }
            } catch(Exception e) {
                XLog.e("", e);
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch(Exception e) {
                        XLog.e("", e);
                    }
                }
                if (out != null) {
                    try {
                        out.close();
                    } catch(Exception e) {
                        XLog.e("", e);
                    }
                }
                if (conn != null) {
                    conn.disconnect();
                }
            }
            return isOk;
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            if (activity != null) {
                Toast.makeText(activity, Consts.UPLOAD_DB_OK, Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(activity, Consts.UPLOAD_DB_FAIL, Toast.LENGTH_LONG).show();
            }
        }
    }
}
